package com.bjsxt.controller;

import com.bjsxt.mapper.SurveyDao;
import com.bjsxt.pojo.*;
import com.bjsxt.service.QuestionServer;
import com.bjsxt.service.SurveyServer;
import com.bjsxt.utils.MapControl;
import com.bjsxt.utils.MapParameter;
import com.bjsxt.utils.SystemStartInit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/survey")
public class SurveyController {

    @Autowired
    private SurveyServer surveyServer;
    @Autowired
    private QuestionServer questionServer;
    @Autowired
    private SurveyDao surveyDao;

    @RequestMapping(value = "/create")
    @ResponseBody
    public String create(Survey survey){
        int result = surveyServer.create(survey);
        if (result<=0){
            return "error";
        }
        return "success";
    }

    @PostMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(String ids){
        int i = surveyServer.deleteBatch(ids);
        if (i<=0){
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }


//    @RequestMapping(value = "/update",produces = "text/html;charset=utf-8")
//    @ResponseBody
//    public String update(Survey survey){
//        int result = surveyServer.update(survey);
//        if (result<=0){
//            return "失败";
//        }
//        return "正确";
//    }

    @PostMapping("/update")
    @ResponseBody
    public Map<String,Object> update(@RequestBody Survey survey){
        survey.setAnon(survey.getAnon()!=null?0:1);
         int update = surveyServer.update(survey);
        if (update<=0){
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }


    @PostMapping("/query")
    @ResponseBody
    public Map<String,Object> query(@RequestBody Survey survey){
        String state = survey.getState();
        //打印查询时传入状态的参数
        System.out.println(state);
        if (state!=null) {
            switch (state) {
                case "0":
                    survey.setState("创建");
                    break;

                case "1":
                    survey.setState("进行中");
                    break;
                case "2":
                    survey.setState("结束");
            }
        }
        //不传参即查询全部用户数据
        List<Survey> data = surveyServer.query(survey);
        for (Survey datum : data) {
            //注意将字符串（creator）转为Integer
            datum.setAdmin(SystemStartInit.map.get(Integer.valueOf(datum.getCreator())));
        }
        //不传参即查询用户总数
        int count = surveyServer.count(survey);
        return MapControl.getInstance().page(data,count).getMap();
    }


    @PostMapping("/queryurl")
    @ResponseBody
    public Map<String,Object> queryUrl(@RequestBody Survey survey){
        String state = survey.getState();
        //打印查询时传入状态的参数
        System.out.println(state);
        if (state!=null) {
            switch (state) {
                case "0":
                    survey.setState("创建");
                    break;

                case "1":
                    survey.setState("进行中");
                    break;
                case "2":
                    survey.setState("结束");
            }
        }
        //不传参即查询全部用户数据
        List<Survey> data = surveyServer.queryUrl(survey);
        for (Survey datum : data) {
            //注意将字符串（creator）转为Integer
            datum.setAdmin(SystemStartInit.map.get(Integer.valueOf(datum.getCreator())));
        }
        //不传参即查询用户总数
        int count = surveyServer.count(survey);
        return MapControl.getInstance().page(data,count).getMap();
    }


   @GetMapping("/detail")
    public String detail(Survey survey, ModelMap modelMap) {

            Survey ad = surveyServer.detail(survey);
            modelMap.addAttribute("survey",ad);
            return "survey/update";
    }


    @GetMapping("/edit")
    public String edit(Survey survey, ModelMap modelMap) {

        Survey ad = surveyServer.detail(survey);
        modelMap.addAttribute("survey",ad);

        return "survey/question";
    }

    @GetMapping("/list")
    public String list(){
        return "survey/list";
    }

    @GetMapping("/add")
    public String v_add(){
        return "survey/add";
    }

    /**
     * 用户管理中实现添加用户操作
     * @param survey
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Map<String,Object> add(@RequestBody Survey survey, HttpServletRequest req){
        Admin admin = (Admin) req.getSession().getAttribute("admin");
//        survey.setCreator(admin.getAccount());
        survey.setCreator(admin.getId()+"");
        survey.setState(Survey.state_create);
        survey.setAnon(survey.getAnon()!=null?0:1);
        int result = surveyServer.create(survey);
        if (result<=0){
            return MapControl.getInstance().error().getMap();
        }

        return MapControl.getInstance().success().getMap();
    }

    /**
     * 预览问卷
     * @param id
     * @param modelMap
     * @return
     */
    @GetMapping("/preview/{id}")
    public String preview(@PathVariable("id") Integer id , ModelMap modelMap) {

        Survey survey = surveyServer.detail(id);


        Question question = new Question();
        question.setSurveyId(survey.getId());
        List<Question> questions = questionServer.query(question);

        survey.setQuestions(questions);

        System.out.println("survey:"+survey.getQuestions().toString());
        modelMap.addAttribute("survey",survey);
        return "survey/preview";
    }

    //上传完成再次定向到预览问卷入口，重新进入加载页面
    @PostMapping("/upload")
    public String upload( Integer id,
                          @RequestParam("file") MultipartFile multipartFile,
                          HttpServletRequest req){

        String path = req.getSession().getServletContext().getRealPath("/upload/");

        File file = new File(path);

        if (!file.exists()){
            file.mkdirs();
        }

        String filename = multipartFile.getOriginalFilename();
        System.out.println("filename"+filename);
        String u = UUID.randomUUID().toString();
        System.out.println("uuid"+u);
        String uuid = u.replace("-", "");
        String savname = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1);

        try {
            multipartFile.transferTo(new File(path,savname));
            Survey survey = new Survey();
            survey.setId(id);
            survey.setBgimg(savname);
            surveyServer.update(survey);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/survey/preview/"+id;

    }

    @PostMapping("release")
    @ResponseBody
    public Map<String,Object> release(Integer id,HttpServletRequest req) {

        String olduuid = UUID.randomUUID().toString();
        String uuid = olduuid.substring(0, olduuid.indexOf("-"));
        String url ="http://"+req.getServerName()+":"+req.getServerPort()+"/release/"+uuid;


        Survey survey = surveyServer.detail(id);

        if (survey != null){
            survey.setUrl(url);
            int update = surveyServer.update(survey);
            if (update>0){
                return MapControl.getInstance().success("发布成功").getMap();
            }
           return MapControl.getInstance().error("发布失败").getMap();
        }

        return MapControl.getInstance().error("用户不存在").getMap();
    }

    @GetMapping("/urlpage")
    public String urlpage(){
        return "survey/urlpage";
    }



    @PostMapping("/submit")
    @ResponseBody
    public Map<String,Object> submit(@RequestBody List<Map<String,Object>> list) {

        List<AnswerOpt> optList = new ArrayList<>();
        List<Answer> txtList = new ArrayList<>();

        String uuid = UUID.randomUUID().toString();

        for (Map<String, Object> stringObjectMap : list) {
            if (object2String(stringObjectMap.get("type")).equals("1") || object2String(stringObjectMap.get("type")).equals("2")){
                //获取选项，并循环赋值对象
                List<Object> opts = (List<Object>) stringObjectMap.get("opts");
                for (Object opt : opts) {
                    AnswerOpt answerOpt = new AnswerOpt();
                    answerOpt.setQuestionId(object2Integet(stringObjectMap.get("questionId")));
                    answerOpt.setSurveyId(object2Integet(stringObjectMap.get("surveyId")));
                    answerOpt.setType(object2String(stringObjectMap.get("type")));
                    answerOpt.setOptId(object2Integet(opt));
                    answerOpt.setCreateTime(new Date());
                    answerOpt.setVoter(uuid);
                    optList.add(answerOpt);
                }
            }
            if (object2String(stringObjectMap.get("type")).equals("3") || object2String(stringObjectMap.get("type")).equals("4")){
                Answer answer = new Answer();
                answer.setQuestionId(object2Integet(stringObjectMap.get("questionId")));
                answer.setSurveyId(object2Integet(stringObjectMap.get("surveyId")));
                answer.setResult(object2String(stringObjectMap.get("result")));
                answer.setCreateTime(new Date());
                answer.setVoter(uuid);
                txtList.add(answer);
            }
        }
        surveyServer.submit(optList,txtList);
        return MapControl.getInstance().success("提交成功").getMap();
    }



    public  String object2String(Object o){

        if (o != null){
            return o+"";
        }
        return null;
    }


    public   Integer object2Integet(Object o){

        if (o != null){
            return Integer.parseInt(o+"");
        }
        return null;
    }

    @RequestMapping("/success")
    public String success(){
        return "survey/success";
    }




}